''' 简易计算器 '''
import tkinter
from tkinter import *
  
#创建横条型框架 
def frame(root, side): 
 f = Frame(root) 
 f.pack(side = side, expand = YES, fill = BOTH) 
 return f 

#定义按钮风格 
def button(root, side, text, command = None): 
 btn = Button(root, text = text, font = ('宋体','12'), command = command) 
 btn.pack(side = side, expand = YES, fill = BOTH) 
 return btn 

#继承了Frame类，初始化程序界面的布局 
class Calculator(Frame): 
 def __init__(self): 
  Frame.__init__(self) 
  self.pack(expand = YES, fill = BOTH) 
  self.master.title('简易计算器') 
  display = StringVar()

  #添加显示数字结果的文本框 
  Entry(self, relief = SUNKEN, font = ('宋体','20','bold'),
      textvariable = display).pack(side = TOP, expand = YES, 
        fill = BOTH) 
 
  #添加清除按钮 
  clearF = frame(self, TOP) #  lambda为匿名函数 
  button(clearF, LEFT, '清除', lambda w = display:w.set('')) 

  #添加横条型框架以及里面的按钮 
  for key in('123+', '456-', '789*', '.0=/'): 
   keyF = frame(self, TOP) 
   for char in key: 
    if char == '=': 
     btn = button(keyF, LEFT, char) 
     btn.bind('<ButtonRelease - 1>', lambda e, s = self, w = display:s.calc(w), '+')
    else:
     btn = button(keyF, LEFT, char, lambda w = display, c = char:w.set(w.get() + c)) 

 #调用eval函数计算表达式的值 
 def calc(self, display): 
  try: 
   display.set(eval(display.get())) 
  except: 
   display.set("ERROR") 

#程序的入口 
if __name__ == '__main__': 
 print('ok') 
 Calculator().mainloop() 
